package net.youdi.gateway.filter;

import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;

import java.util.*;

/**
 * @author: scl
 * @date:2020-04-06 16:30
 * @description
 */
public class CorsHeadersFilter  implements HttpHeadersFilter, Ordered {

    /**
     * Headers to remove as the result of applying the filter.
     */
    public static final Set<String> HEADERS_REMOVED_ON_RESPONSE = new HashSet<>(Arrays.asList("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));

    @Override
    public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
        for (Map.Entry<String, List<String>> entry : input.entrySet()) {
            if (HEADERS_REMOVED_ON_RESPONSE.contains(entry.getKey())){
                List<String> value = entry.getValue();
                if (value.size()>1){
                    input.put(entry.getKey(),Arrays.asList(value.get(0)));
                }
            }
        }
        return input;
    }

    @Override
    public boolean supports(Type type) {
        return type.equals(Type.RESPONSE);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
